<?php

namespace services\buss;

use api\modules\common\services\UploadService;
use api\modules\v1\forms\buss\ToolWaterForm;
use common\components\Service;
use common\helpers\DateHelper;
use common\helpers\RedisHelper;
use common\models\buss\ToolWater;
use common\models\sys\SysFile;
use services\log\LogMemberOpService;
use services\member\MemberService;
use services\sys\SysFileService;
use Yii;

/**
 * Class ToolWaterService
 * @package services\buss
 */
class ToolWaterService extends Service
{
    /**
     * 水印列表
     * @param array $params
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public function getListPage(array $params = [], int $page = 0, int $pageSize = 0): array
    {
        $query = ToolWater::find()
            ->select(['*'])
            ->where([
                'project_id' => array_column(MemberService::getProjectListCondition(), 'value'),
                'status' => ToolWater::STATUS_ENABLE
            ]);
        // 排序
        $order = ['created_at' => SORT_DESC, 'id' => SORT_DESC];

        return $this->getListPageRes($query, $page, $pageSize, $order);
    }

    /**
     * 格式化列表
     * @param array $data
     * @return array
     */
    public function getListPageFormat(array $data = []): array
    {
        $list = [];
        foreach ($data as $row) {
            $fileUrl = $row['file'] ? UploadService::getFileTrueUrl(SysFile::SITE_TOOL, SysFile::MODULE_TOOL_WATER, $row['file']) : '';
            $list[] = [
                'id' => $row['id'],
                'project_name' => RedisHelper::getProject($row['project_id'])->project_name ?? '',
                'type' => $row['type'],
                'type_str' => ToolWater::$types[$row['type']] ?? '',
                'text' => $row['text'],
                'file_url' => $fileUrl,
                'alpha' => $row['alpha'],
                'created_member_name' => RedisHelper::getMember($row['created_member_id'])->realname ?? '',
                'created_at_str' => DateHelper::timestampToDate($row['created_at'], DateHelper::DATE_FORMAT_4),
            ];
        }
        return $list;
    }

    /**
     * 获取项目水印配置信息
     * @param int $projectId
     * @return array
     */
    public static function getProjectWaterData(int $projectId): array
    {
        $toolWater = ToolWater::findOne([
            'project_id' => $projectId,
            'status' => ToolWater::STATUS_ENABLE
        ]);
        $filePath = $toolWater && $toolWater->file ? UploadService::getFileTruePath(SysFile::SITE_TOOL, SysFile::MODULE_TOOL_WATER, $toolWater->file) : '';
        return [
            'type' => $toolWater->type ?? 0,// 0未配置 1文字、2图片
            'text' => $toolWater->text ?? '',
            'file' => $filePath,
            'alpha' => $toolWater->alpha ?? 0,
        ];
    }

    public static function getTypeCondition(): array
    {
        $types = ToolWater::$types;
        $data = [];
        foreach ($types as $key => $val) {
            $data[] = [
                'value' => $key,
                'label' => $val,
            ];
        }
        return $data;
    }

    /**
     * 获取水印编辑详情
     * @param array $params
     * @return array
     */
    public function getEditInfo(int $id): array
    {
        $data = [
            'support_image_type' => UploadService::$imageTypeArr[3],
        ];
        // 工具信息
        $toolWater = ToolWater::findOne($id);
        if ($toolWater) {
            $data = array_merge($data, [
                'id' => $toolWater->id,
                'project_id' => $toolWater->project_id,
                'type' => $toolWater->type,
                'text' => $toolWater->text,
                'file' => $toolWater->file,
                'file_url' => $toolWater->file ? UploadService::getFileTrueUrl(SysFile::SITE_TOOL, SysFile::MODULE_TOOL_WATER, $toolWater->file) : '',
                'alpha' => $toolWater->alpha,
            ]);
        }
        $condition = [
            'project' => MemberService::getProjectEditCondition($data['project_id'] ?? null),
            'type' => self::getTypeCondition(),
        ];
        if ($toolWater) {
            if (in_array($data['project_id'], array_column($condition['project'], 'value')) === false) {
                $data['project_id'] = 0;
            }
        }
        return array_merge($data, ['condition' => $condition]);
    }

    /**
     * 编辑工具
     * @param ToolWater $toolWater
     * @param ToolWaterForm $model
     * @return ToolWater
     * @throws \Exception
     */
    public static function editModel(ToolWater $toolWater, ToolWaterForm $model): ToolWater
    {
        $toolWater->project_id = $model->project_id;
        $toolWater->type = $model->type;
        $toolWater->text = $model->type == ToolWater::TYPE_TEXT ? $model->text : '';
        $toolWater->file = $model->type == ToolWater::TYPE_FILE ? $model->file : '';
        $toolWater->alpha = $model->alpha;
        if ($model->getScenario() == 'create') {
            $toolWater->created_member_id = Yii::$app->user->identity->member_id;
            $toolWater->operation_id = Yii::$app->user->identity->member_id;
            $toolWater->operation_name = Yii::$app->user->identity->member->realname;
        }
        $toolWater->status = ToolWater::STATUS_ENABLE;
        $toolWater->saveAndCheckResult();

        return $toolWater;
    }

    /**
     * 新增水印
     * @param ToolWaterForm $model
     * @return array
     */
    public function create(ToolWaterForm $model): array
    {
        try {
            $transaction = Yii::$app->db->beginTransaction();

            // 1.新增水印
            $toolWater = new ToolWater();
            $toolWater = self::editModel($toolWater, $model);
            // 2.更新图片信息
            if ($toolWater->type == ToolWater::TYPE_FILE) {
                SysFileService::editFile(SysFile::SITE_TOOL, SysFile::MODULE_TOOL_WATER, $model->file);
            }
            // 3.日志
            LogMemberOpService::createToolWaterLog($model, $toolWater);

            $transaction->commit();
            return ['id' => $toolWater->id];
        } catch (\Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
    }

    /**
     * 编辑水印
     * @param ToolWaterForm $model
     * @return array
     */
    public function edit(ToolWaterForm $model): array
    {
        try {
            $transaction = Yii::$app->db->beginTransaction();

            // 1.更新水印
            $oldToolWater = new ToolWater();
            $oldToolWater->setAttributes($model->getToolWater()->getAttributes());
            $toolWater = self::editModel($model->getToolWater(), $model);
            // 2.更新图片信息
            if ($toolWater->type == ToolWater::TYPE_FILE && $toolWater->file != $oldToolWater->file) {
                SysFileService::editFile(SysFile::SITE_TOOL, SysFile::MODULE_TOOL_WATER, $toolWater->file, $oldToolWater->file);
            }
            // 3.日志
            if (LogMemberOpService::createToolWaterLog($model, $toolWater, $oldToolWater)) {
                $toolWater->operation_id = Yii::$app->user->identity->member_id;
                $toolWater->operation_name = Yii::$app->user->identity->member->realname;
                $toolWater->saveAndCheckResult();
            }

            $transaction->commit();
            return ['id' => $toolWater->id];
        } catch (\Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
    }

    /**
     * 删除水印
     * @param ToolWaterForm $model
     * @return array
     */
    public function delete(ToolWaterForm $model): array
    {
        try {
            $transaction = Yii::$app->db->beginTransaction();

            // 1.更新工具
            $toolWater = $model->getToolWater();
            $toolWater->status = ToolWater::STATUS_DELETE;
            $toolWater->operation_id = Yii::$app->user->identity->member_id;
            $toolWater->operation_name = Yii::$app->user->identity->member->realname;
            $toolWater->saveAndCheckResult();
            // 2.更新附件信息
            SysFileService::editFile(SysFile::SITE_TOOL, SysFile::MODULE_TOOL_WATER, '', $toolWater->file);
            // 3.日志
            LogMemberOpService::createToolWaterLog($model, $toolWater);

            $transaction->commit();
            return ['id' => $toolWater->id];
        } catch (\Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
    }
}
